<template>
    <div class="qr-scanner">
        <div class="box">
            <div :class="['line', {'stop': stop}] "></div>
            <div class="angle"></div>
            <div class="face-wrap">
                <video id="video" width="705" height="705" ref="video" autoplay></video>
                <canvas style="display:none;" id="canvas" width="705" height="705" ref="canvas"></canvas>
            </div>
            <div class="border1"></div>
            <div class="border2"></div>
        </div>
        <div class="btn" style="display: none"></div>
    </div>
</template>

<script>
    import {faceLogin} from "../../api/face";
    import { setToken, setUserInfo } from "../../common/js/cache";
    import { searchUserInfo } from "../../api/login";
    import { ERROR_NO } from "../../util/config";
    export default {
    data () {
        return {
            stop: false
        }
    },
    methods: {
        _searchUserInfo(id) {
            searchUserInfo(id).then(res => {
                if (res.code === ERROR_NO) {
                    setUserInfo(res.data.userInfo)
                }
            })
        },
    },
    mounted () {
        const canvas = this.$refs.canvas
        const video = this.$refs.video
        const context = canvas.getContext('2d')
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {}
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function (constraints) {
                // 首先获取现存的getUserMedia(如果存在)
                const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
                // 有些浏览器不支持，会返回错误信息
                // 保持接口一致
                if (!getUserMedia) {
                    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                }
                //否则，使用Promise将调用包装到旧的navigator.getUserMedia
                return new Promise(function (resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                })
            }
        }
        const constraints = {audio: false, video: {width: 300, height: 300}}
        navigator.mediaDevices.getUserMedia(constraints)
            .then(function (stream) {
                const video = document.querySelector('video');
                // 旧的浏览器可能没有srcObject
                if ("srcObject" in video) {
                    video.srcObject = stream;
                } else {
                    //避免在新的浏览器中使用它，因为它正在被弃用。
                    video.src = window.URL.createObjectURL(stream);
                }
                video.onloadedmetadata = function (e) {
                    console.log(e)
                    video.play()
                }
            })
            .catch(function (err) {
                console.log(err.name + ": " + err.message)
            })
        // const btn = document.getElementsByClassName('btn')[0]
        this.timer = setInterval(() => {
            // 点击，canvas画图
            context.drawImage(video, 0, 0, 705, 705);
            // 获取图片base64链接
            var image = canvas.toDataURL('image/png');
            // base64转文件
            function dataURLtoFile(dataurl, filename) {
                var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {type: mime});
            }
            const file = dataURLtoFile(image, 'aa.png')
            const formData = new FormData()
            formData.set('file', file)
            faceLogin(formData).then(res => {
                if (res.code === 200) {
                    clearInterval(this.timer)
                    const token = res.data.userInfo.Token
                    setToken(token)
                    this._searchUserInfo(res.data.userInfo.userId)
                    this.$message({
                        message: '人脸识别成功',
                        type: 'success'
                    });
                    setTimeout(() =>{
                        this.$router.push('/home')
                        window.location.reload()
                    }, 2000)
                    return
                }
                this.$message({
                    message: '请对准屏幕',
                    duration: 500
                });
            })
        }, 1000)
        // btn.addEventListener("click", function () {
        //     // 点击，canvas画图
        //     context.drawImage(video, 0, 0, 705, 705);
        //     // 获取图片base64链接
        //     var image = canvas.toDataURL('image/png');
        //     // base64转文件
        //     function dataURLtoFile(dataurl, filename) {
        //         var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        //             bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        //         while (n--) {
        //             u8arr[n] = bstr.charCodeAt(n);
        //         }
        //         return new File([u8arr], filename, {type: mime});
        //     }
        //     const file = dataURLtoFile(image, 'aa.png')
        //     const formData = new FormData()
        //     formData.set('file', file)
        //     faceLogin(formData).then(res => {
        //         console.log(res)
        //     })
        // })
        // setTimeout(() => {
        //     this.$notify({
        //         title: '提示',
        //         message: '登陆成功',
        //         type: 'succeess',
        //         duration: 1500
        //     })
        //     setTimeout(() => {
        //         this.$router.push('/home')
        //     }, 100)
        //     this.stop = true
        // }, 5000)
    }
}
</script>

<style scoped lang="scss">
    .qr-scanner {
        position: fixed;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        background-image:
                linear-gradient(0deg,
                        transparent 24%,
                        rgba(32, 255, 77, 0.1) 25%,
                        rgba(32, 255, 77, 0.1) 26%,
                        transparent 27%,
                        transparent 74%,
                        rgba(32, 255, 77, 0.1) 75%,
                        rgba(32, 255, 77, 0.1) 76%,
                        transparent 77%,
                        transparent),
                linear-gradient(90deg,
                        transparent 24%,
                        rgba(32, 255, 77, 0.1) 25%,
                        rgba(32, 255, 77, 0.1) 26%,
                        transparent 27%,
                        transparent 74%,
                        rgba(32, 255, 77, 0.1) 75%,
                        rgba(32, 255, 77, 0.1) 76%,
                        transparent 77%,
                        transparent);
        background-size: 3rem 3rem;
        background-position: -1rem -1rem;
        width: 100%;
        height: 100%;
        background-color: #111;
        .face-wrap {
            position: absolute;
            top: 0;
            right: 0;
            left: 0;
            bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .box {
            width: 75vw;
            height: 75vw;
            max-height: 75vh;
            max-width: 75vh;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            overflow: hidden;
            border: 0.1rem solid rgba(0, 255, 51, 0.2);
            &::before {
                content: "";
                position: absolute;
                top: 0;
                right: 0;
                border: 0.2rem solid transparent;
                border-right-color: #00ff33;
                border-top-color: #00ff33;
                width: 55px;
                height: 55px;
                z-index: 3;
            }

            &::after {
                content: "";
                width: 55px;
                height: 55px;
                position: absolute;
                bottom: 0;
                right: 0;
                border: 0.2rem solid transparent;
                border-right-color: #00ff33;
                border-bottom-color: #00ff33;
            }

            .border1 {
                width: 55px;
                height: 55px;
                z-index: 3;
                position: absolute;
                top: 0;
                left: 0;
                border: 0.2rem solid transparent;
                border-left-color: #00ff33;
                border-top-color: #00ff33;
            }

            .border2 {
                width: 55px;
                height: 55px;
                z-index: 3;
                position: absolute;
                bottom: 0;
                left: 0;
                border: 0.2rem solid transparent;
                border-left-color: #00ff33;
                border-bottom-color: #00ff33;
            }
        }
        .line {
            position: relative;
            z-index: 999;
            height: calc(100% - 2px);
            width: 100%;
            background: linear-gradient(180deg, rgba(0, 255, 51, 0) 43%, #00ff33 211%);
            border-bottom: 3px solid #00ff33;
            transform: translateY(-100%);
            animation: radar-beam 2s infinite;
            animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
            animation-delay: 1.4s;
        }
        .stop {
            animation-play-state: paused;
        }
    }
    @keyframes radar-beam {
        0% {
            transform: translateY(-100%);
        }

        100% {
            transform: translateY(0);
        }
    }
</style>
